package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import com.amap.api.services.core.AMapException
import com.amap.api.services.weather.LocalWeatherForecastResult
import com.amap.api.services.weather.LocalWeatherLive
import com.amap.api.services.weather.LocalWeatherLiveResult
import com.amap.api.services.weather.WeatherSearch
import com.amap.api.services.weather.WeatherSearchQuery
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.RaceDetailInfoResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentOrgPassDetailBinding
import com.gexiaobao.pigeon.ui.activity.ActivityGameResult
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityCarVehicleRoute
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityFlyMap
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPigeonGatheringDetail
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/7/23 15:36
 * @Describe    : 关卡详情
 */
class FragmentOrgPassDetail : BaseFragment<RaceViewModel, FragmentOrgPassDetailBinding>(), WeatherSearch.OnWeatherSearchListener {

    private var mId = 0
    private var mMapId = 0
    private var mRaceId = 0
    private var memberCode = ""//获取棚号
    private var title = ""
    private var passStatus: String = ""
    private lateinit var mResultData: RaceDetailInfoResponse

    //查询实时天气相关
    private var weatherlive: LocalWeatherLive? = null
    private lateinit var mQuery: WeatherSearchQuery
    private lateinit var mWeatherSearch: WeatherSearch
    private val sharedViewModel: SharedViewModel by activityViewModels()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        title = getString(R.string.this_is_race_name)
        mId = requireArguments().getInt("passId")
        mRaceId = requireArguments().getInt("raceId")
        title = arguments?.getString("title").toString()
        passStatus = arguments?.getString("passStatus").toString()
        mViewModel.flyingState.set(passStatus == "6")

        mDatabind.swipeRefreshView.init {
            showLoading(getString(R.string.loading))
            mViewModel.getPassDetailApp(mId.toString())
        }

        sharedViewModel.data.observe(viewLifecycleOwner) {
            title = it.titleName
            mRaceId = it.raceId
            mId = it.id
            mViewModel.getPassDetailApp(mId.toString())
        }
    }

    override fun initData() {
        super.initData()
        mResultData = RaceDetailInfoResponse()
        searchLiveWeather()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.raceDetailGeneralFlyedMap,
            mDatabind.raceDetailGeneralCarMap,
            mDatabind.raceDetailGeneralRaceResult,
            mDatabind.raceDetailGeneralCollectionPigDetail
        ) {
            when (it) {
                mDatabind.raceDetailGeneralFlyedMap -> {
                    if (passStatus.toInt() < 6) {
                        showMessage(getString(R.string.no_fly_and_wait_look))
                        return@setOnclickNoRepeat
                    }
                    startActivity<ActivityFlyMap>("passId" to mId, "title" to title)
                }

                mDatabind.raceDetailGeneralCarMap -> {
                    startActivity<ActivityCarVehicleRoute>("title" to title, "id" to mMapId)
                }

                mDatabind.raceDetailGeneralRaceResult -> {
                    startActivity<ActivityGameResult>("title" to title, "passId" to mMapId, "type" to "race", "raceId" to mRaceId)
                    activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                }

                mDatabind.raceDetailGeneralCollectionPigDetail -> {
                    startActivity<ActivityPigeonGatheringDetail>(
                        "passId" to mId,
                        "title" to title,
                        "memberCode" to memberCode,
                        "raceId" to mRaceId
                    )
                }
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading(getString(R.string.loading))
        mViewModel.getMemberNum(mId.toString())
        mViewModel.getPassDetailApp(mId.toString())
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.detailInfoResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (mDatabind.swipeRefreshView.isRefreshing) {
                mDatabind.swipeRefreshView.isRefreshing = false
            }
            if (it != null) {
                mResultData = it
                mMapId = it.id
                mViewModel.gatherPigeonsTime.set(it.loadTime)
                mViewModel.gatherPigeonsAddress.set(it.loadPlace)
                mViewModel.gatherPigeonsMobile.set(it.loadPhone)
                mViewModel.trainingPigeonsAddress.set(it.flyPlace)
                mViewModel.signUpFeatherNum.set(it.signNum)
                mViewModel.intoCageFeatherNum.set(it.loadedNum)
                mViewModel.homingNum.set(it.backNum)
                mViewModel.trainingWeather.set(it.weather)
                mViewModel.airTemperature.set(it.temperature)
                mViewModel.windPower.set(it.wind.trim())
                mViewModel.gap.set(it.flyDis)
                mViewModel.longitude.set(it.flyLonShow)
                mViewModel.latitude.set(it.flyLatShow)
                mViewModel.refereeZ.set(it.headReferee)
                mViewModel.refereeY.set(it.referee)
                mViewModel.pilot.set(it.flyMan)
                mViewModel.trainingPigeonsTime.set(it.flyTime)
            } else {
                RxToast.showToast(getString(R.string.no_get_information))
            }
        }

        /**  获取棚号  */
        mViewModel.memberNumResult.observe(viewLifecycleOwner) {
            if (it != null) {
                memberCode = it.memberNum
            }
        }
    }

    private fun searchLiveWeather() {
        mQuery = WeatherSearchQuery(getString(R.string.qingdao_city), WeatherSearchQuery.WEATHER_TYPE_LIVE) //检索参数为城市和天气类型，实时天气为1、天气预报为2
        try {
            mWeatherSearch = WeatherSearch(context)
            mWeatherSearch.setOnWeatherSearchListener(this)
            mWeatherSearch.query = mQuery
            mWeatherSearch.searchWeatherAsyn() //异步搜索
        } catch (e: AMapException) {
            e.printStackTrace()
        }
    }

    companion object {
        fun newInstance(raceId: Int, passId: Int, title: String, passStatus: String): FragmentOrgPassDetail {
            val fragment = FragmentOrgPassDetail()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("passId", passId)
            bundle.putString("title", title)
            bundle.putString("passStatus", passStatus)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onWeatherLiveSearched(weatherLiveResult: LocalWeatherLiveResult?, rCode: Int) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (weatherLiveResult?.liveResult != null) {
                weatherlive = weatherLiveResult.liveResult
            } else {
                RxToast.showToast(getString(R.string.sorry_no_search_data))
            }
        } else {
            RxToast.showToast(rCode.toString())
        }
    }

    override fun onWeatherForecastSearched(p0: LocalWeatherForecastResult?, p1: Int) {

    }
}